package org.wevil.util;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 数组工具类
 *
 * @author wanglei
 * @since 2020/9/11
 */
public class ArrayUtil {

    /**
     * 两个数组合并
     *
     * @since 2022/4/13
     */
    public static <T> T[] combine(T[] arr1, T[] arr2, Class<T> clazz) {
        List<T> list1 = Arrays.asList(arr1);
        List<T> list2 = Arrays.asList(arr2);
        List<T> combineList = new ArrayList<>();
        combineList.addAll(list1);
        combineList.addAll(list2);
        T[] ts = (T[]) Array.newInstance(clazz, 0);
        return combineList.toArray(ts);
    }

    /**
     * 字符串数组转换为数字数组
     *
     * @since 2022/2/28
     */
    public static List<Integer> str2int(String[] strings) {
        List<Integer> list = new ArrayList<>();
        Arrays.stream(strings).forEach(str -> list.add(Integer.valueOf(str)));
        return list;
    }

    /**
     * 数组反转
     *
     * @author wanglei
     * @since 2021/7/13
     */
    public static <E> E[] reverse(E[] arrays, Class<E> clz) {
        E[] temp = (E[]) Array.newInstance(clz, arrays.length);
        //存放元素
        List<E> list = new ArrayList<>(Arrays.asList(arrays));
        Collections.reverse(list); //使用方法进行逆序
        //完成逆序后,可以保存到新数组reverseArray
        for (int i = 0; i < arrays.length; i++) {
            Array.set(temp, i, list.get(i));
        }
        return temp;
    }
}
